//
//  UIAlertView+Block.m
//  Yanwei
//
//  Created by 刘文 on 16/9/28.
//  Copyright © 2016年 DCloud. All rights reserved.
//

#import "UIAlertView+Block.h"
#import <objc/runtime.h>

@implementation UIAlertView (Block)

static char key;

- (void)showAlertViewWithCompleteBlock:(CompleteBlock)block {
    // set key & delegate
    if (block) {
        objc_removeAssociatedObjects(self);
        objc_setAssociatedObject(self, &key, block, OBJC_ASSOCIATION_COPY);
        self.delegate = self;
    }
    // show
    [self show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    CompleteBlock block = objc_getAssociatedObject(self, &key);
    if (block) {
        block(buttonIndex);
    }
}

void AlertWithMessage(NSString * message, CompleteBlock block) {
    NSString * btnOK = NSLocalizedStringFromTable(@"OK", @"确定", nil);
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:message message:nil delegate:nil cancelButtonTitle:btnOK otherButtonTitles:nil, nil];
    [alert showAlertViewWithCompleteBlock:block];
}

void AlertWithSelections(NSString * message, NSString * btnNO, NSString * btnYES, CompleteBlock block) {
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:message message:nil delegate:nil cancelButtonTitle:btnNO otherButtonTitles:btnYES, nil];
    [alert showAlertViewWithCompleteBlock:block];
}

@end
